package com.xiaoyun.advicetemplate.handler;

import com.xiaoyun.advicetemplate.annotation.ResultAdvice;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Method;

import static com.xiaoyun.advicetemplate.config.Constant.HAS_RESULT_ADVICE;

@Component
public class ResultAdviceHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanType = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();
            if (beanType.isAnnotationPresent(ResultAdvice.class)) {
                request.setAttribute(HAS_RESULT_ADVICE, beanType.getAnnotation(ResultAdvice.class));
            } else if (method.isAnnotationPresent(ResultAdvice.class)) {
                request.setAttribute(HAS_RESULT_ADVICE, method.getAnnotation(ResultAdvice.class));
            }
        }
        return true;
    }
}
